package com.luyu.datapermission;

import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.luyu.tenant.TenantContextHolder;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;

import java.util.HashMap;
import java.util.List;

// 处理数据隔离插件

public class BaseDataPermissionHandler implements MultiDataPermissionHandler {

    private FieldDataPermissionSqlImpl fieldDataPermission;

    public BaseDataPermissionHandler(FieldDataPermissionSqlImpl fieldDataPermission) {
        this.fieldDataPermission = fieldDataPermission;
    }

    // 整张表需要控制数据权限的字段
    private HashMap<String,String> map=new HashMap<>();

    {
        map.put("product","unit_id");
    }

    @Override
    public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
        // 如果是登录接口
        if (TenantContextHolder.getTenantId() == null) {
            return null;
        }

        // 在此处编写自定义数据权限逻辑
        // 1 获取表中需要数据权限控制的字段
        String filedName=map.getOrDefault(table.getName(),"");
        if (filedName.isBlank()) {
            return null;
        }
        try {
            //  2 拼接需要链接的数据权限sql
            String sqlSegment = fieldDataPermission.getConditionSql(List.of(filedName));
            Expression expression = CCJSqlParserUtil.parseCondExpression(sqlSegment);
            return expression;
        } catch (JSQLParserException e) {
            e.printStackTrace();
            return null;
        }
    }


}
